<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="开始范围" prop="start">
        <el-input
          v-model="queryParams.start"
          placeholder="请输入开始范围"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结束范围" prop="end">
        <el-input
          v-model="queryParams.end"
          placeholder="请输入结束范围"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:wordConf:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:wordConf:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:wordConf:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:wordConf:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar
        :search="false"
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="wordConfList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="字数区间" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.start +
            (scope.row.type === 0 ? "~" + scope.row.end : "及以上")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ timestampToDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:wordConf:edit']"
            >修改</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:wordConf:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="formGroup">
          <el-form-item
            label="字数区间"
            prop="start"
            v-if="form.type == 0"
            class="formGroup-item1"
          >
            <el-input
              v-model="form.start"
              placeholder="请输入字数"
              type="number"
            />
          </el-form-item>
          <el-form-item
            prop="end"
            v-if="form.type == 0"
            class="formGroup-item1"
            label-width="0"
          >
            <el-input
              v-model="form.end"
              placeholder="请输入字数"
              type="number"
            />
          </el-form-item>
          <el-form-item
            label="字数区间"
            v-if="form.type == 1"
            class="formGroup-item2"
            prop="start"
          >
            <el-input
              v-model="form.start"
              placeholder="请输入字数"
              type="number"
            />
          </el-form-item>
          <el-form-item prop="type" label-width="0">
            <el-radio-group v-model="form.type" inline @change="radioChange">
              <el-radio-button label="1">以上</el-radio-button>
              <el-radio-button label="0">范围</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </div>
        <el-form-item label="显示排序" prop="id">
          <el-input v-model="form.id" placeholder="请输入序号" type="number" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWordConf,
  getWordConf,
  delWordConf,
  addWordConf,
  updateWordConf,
} from "@/api/system/wordConf";
import { timestampToDate } from "@/utils/time";
export default {
  name: "WordConf",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 字数区间配置表格数据
      wordConfList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        start: null,
        end: null,
      },
      // 表单参数
      form: {
        type: 0,
      },
      // 表单校验
      rules: {
        type: [
          {
            required: true,
            message: "类型 0 区间 1 以上不能为空",
            trigger: "change",
          },
        ],
        start: [
          { required: true, message: "开始范围不能为空", trigger: "blur" },
        ],
        end: [{ required: true, message: "结束范围不能为空", trigger: "blur" }],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" },
        ],
        type: [
          {
            required: true,
            message: "请选择类型 0  以上 范围 1",
            trigger: "change",
          },
        ],
        id: [{ required: true, message: "序号不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    window.addEventListener("beforeunload", this.handleBeforeUnload);
  },
  methods: {
    timestampToDate,
    /** 查询字数区间配置列表 */
    getList() {
      this.loading = true;
      listWordConf(this.queryParams).then((response) => {
        this.wordConfList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: 0,
        start: null,
        end: null,
        createTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加字数区间配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getWordConf(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改字数区间配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (
            this.form.type === 0 &&
            this.form.start * 1 >= this.form.end * 1
          ) {
            this.$modal.msgError("区间范围错误");
            return;
          }
          if (this.form.id != null) {
            updateWordConf({
              ...this.form,
              start: Number(this.form.start),
              end: Number(this.form.end),
            }).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWordConf({
              ...this.form,
              start: Number(this.form.start),
              end: Number(this.form.end),
            }).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除字数区间配置编号为"' + ids + '"的数据项？')
        .then(function () {
          return delWordConf(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/wordConf/export",
        {
          ...this.queryParams,
        },
        `wordConf_${new Date().getTime()}.xlsx`
      );
    },

    handleBeforeUnload(event) {
      if (!this.canLeave) {
        const confirmationMessage = "确定要离开该页面吗？";
        event.returnValue = confirmationMessage;
        return confirmationMessage;
      }
    },
    radioChange(e) {
      if (e == 1) {
        this.form.end = 0;
      }
    },
  },

  computed: {
    canLeave() {
      if (!this.wordConfList.length) return true;
      let endResult = this.wordConfList.filter((item) => item.type === 1);
      if (endResult.length && endResult.length === 1) return true; // 结束区间只有一个
      return false;
    },
  },

  beforeRouteLeave(to, from, next) {
    if (this.canLeave) {
      next();
    } else {
      if (confirm("配置不正确，请修改配置？")) {
        next(false);
      } else {
        next(false);
      }
    }
  },
  destroyed() {
    window.removeEventListener("beforeunload", this.handleBeforeUnload);
  },
};
</script>

<style>
.formGroup {
  display: flex;
  align-items: center;
  gap: 10px;
}

.formGroup-item1 .el-input {
  width: 110px;
}

.el-radio-group {
  width: 140px;
}
</style>
